<template>
  <div class="flex flex-col h-full overflow-hidden">
    <app-header :show-back-button="true"/>

    <main class="flex-grow p-4 flex flex-col overflow-hidden">
      <h2 class="page-title text-center text-lg font-bold text-[var(--text-primary)] mb-3 flex-shrink-0">报警 /
        事件日志</h2>

      <div
          class="filter-area bg-[var(--bg-secondary)] p-3 rounded-md mb-4 flex flex-wrap gap-4 items-center border border-[var(--border-color)] shadow-sm flex-shrink-0">
        <div class="filter-group flex items-center gap-1.5">
          <label for="filter-log-type"
                 class="filter-label text-sm font-medium text-[var(--text-secondary)]">类型:</label>
          <select
              id="filter-log-type"
              v-model="filters.type"
              class="filter-select px-2 py-1 border border-[var(--border-color)] rounded-md text-sm bg-[#f9fafb] focus:outline-none focus:border-[var(--accent-blue)]"
          >
            <option value="">所有</option>
            <option value="Alarm">报警</option>
            <option value="Event">事件</option>
            <option value="Info">信息</option>
          </select>
        </div>

        <div class="filter-group flex items-center gap-1.5">
          <label for="filter-log-code"
                 class="filter-label text-sm font-medium text-[var(--text-secondary)]">代码:</label>
          <input
              type="text"
              id="filter-log-code"
              v-model="filters.code"
              class="filter-input px-2 py-1 border border-[var(--border-color)] rounded-md text-sm bg-[#f9fafb] focus:outline-none focus:border-[var(--accent-blue)]"
              placeholder="输入报警/事件代码"
          />
        </div>

        <div class="filter-group flex items-center gap-1.5">
          <label for="filter-log-date"
                 class="filter-label text-sm font-medium text-[var(--text-secondary)]">日期:</label>
          <input
              type="date"
              id="filter-log-date"
              v-model="filters.date"
              class="filter-input px-2 py-1 border border-[var(--border-color)] rounded-md text-sm bg-[#f9fafb] focus:outline-none focus:border-[var(--accent-blue)]"
          />
        </div>

        <button @click="applyFilters"
                class="hmi-button hmi-button-primary px-3 py-1.5 rounded-md text-sm font-semibold flex items-center gap-1 ml-auto">
          <i class="fas fa-filter"></i> 应用筛选
        </button>
        <button @click="refreshLogs"
                class="hmi-button hmi-button-secondary px-3 py-1.5 rounded-md text-sm font-semibold flex items-center gap-1"
                :disabled="isLoading">
          <i class="fas fa-sync-alt" :class="{'fa-spin': isLoading}"></i> 刷新
        </button>
        <button @click="exportLogs"
                class="hmi-button hmi-button-secondary px-3 py-1.5 rounded-md text-sm font-semibold flex items-center gap-1">
          <i class="fas fa-file-export"></i> 导出日志
        </button>
      </div>

      <div
          class="log-table-container flex-grow overflow-y-auto bg-[var(--bg-secondary)] rounded-md border border-[var(--border-color)] shadow-sm">
        <!-- 加载状态显示 -->
        <div v-if="isLoading" class="flex flex-col items-center justify-center h-full p-6">
          <i class="fas fa-spinner fa-spin text-3xl text-[var(--accent-blue)] mb-3"></i>
          <p class="text-[var(--text-secondary)]">正在加载日志数据...</p>
        </div>

        <table v-else class="log-table w-full border-collapse text-sm">
          <thead>
          <tr>
            <th class="col-timestamp px-3 py-2 text-left border-b border-[var(--border-color)] bg-[#f9fafb] font-semibold text-[var(--text-secondary)] sticky top-0 z-10 whitespace-nowrap">
              时间戳
            </th>
            <th class="col-type px-3 py-2 text-center border-b border-[var(--border-color)] bg-[#f9fafb] font-semibold text-[var(--text-secondary)] sticky top-0 z-10 whitespace-nowrap">
              类型
            </th>
            <th class="col-code px-3 py-2 text-left border-b border-[var(--border-color)] bg-[#f9fafb] font-semibold text-[var(--text-secondary)] sticky top-0 z-10 whitespace-nowrap">
              代码/ID
            </th>
            <th class="col-desc px-3 py-2 text-left border-b border-[var(--border-color)] bg-[#f9fafb] font-semibold text-[var(--text-secondary)] sticky top-0 z-10 whitespace-nowrap">
              描述
            </th>
          </tr>
          </thead>
          <tbody>
          <tr
              v-for="(log, index) in paginatedLogs"
              :key="index"
              class="hover:bg-[#f0f4f8]"
          >
            <td class="col-timestamp px-3 py-2 border-b border-[var(--border-color)] whitespace-nowrap">{{
                log.timestamp
              }}
            </td>
            <td class="col-type px-3 py-2 border-b border-[var(--border-color)] text-center font-semibold whitespace-nowrap"
                :class="getLogTypeClass(log.type)">{{ log.type }}
            </td>
            <td class="col-code px-3 py-2 border-b border-[var(--border-color)] whitespace-nowrap">{{
                log.code || '-'
              }}
            </td>
            <td class="col-desc px-3 py-2 border-b border-[var(--border-color)] whitespace-normal break-all">
              {{ log.description }}
            </td>
          </tr>
          <tr v-if="paginatedLogs.length === 0">
            <td colspan="4" class="px-3 py-4 text-center text-[var(--text-secondary)]">无匹配的日志记录</td>
          </tr>
          </tbody>
        </table>
      </div>

      <div
          class="pagination-area bg-[var(--bg-secondary)] p-2 border-t border-[var(--border-color)] flex justify-between items-center flex-shrink-0 text-sm text-[var(--text-secondary)]">
        <span id="pagination-info" class="pagination-info font-medium">
            第 {{ totalPages === 0 ? 0 : currentPage }} 页 / 共 {{ totalPages }} 页 (共 {{ filteredLogs.length }} 条)
        </span>
        <div class="pagination-controls">
          <button
              id="btn-prev-page"
              @click="changePage(-1)"
              class="hmi-button hmi-button-secondary px-3 py-1 rounded-md text-sm font-semibold flex items-center gap-1"
              :disabled="currentPage <= 1"
          >
            <i class="fas fa-chevron-left"></i> 上一页
          </button>
          <button
              id="btn-next-page"
              @click="changePage(1)"
              class="hmi-button hmi-button-secondary px-3 py-1 rounded-md text-sm font-semibold flex items-center gap-1"
              :disabled="currentPage >= totalPages"
          >
            下一页 <i class="fas fa-chevron-right"></i>
          </button>
        </div>
      </div>
    </main>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted, computed} from 'vue';
import {useRouter} from 'vue-router';
import AppHeader from '@/components/AppHeader.vue'; // 导入 useRouter

const router = useRouter(); // 获取路由实例

// --- 响应式数据 ---
// 原始日志数据
const allAlarmLogData = reactive([]);

// 加载状态
const isLoading = ref(false);

// 筛选条件
const filters = reactive({
  type: '',
  code: '',
  date: ''
});

// 分页状态
const currentPage = ref(1);
const itemsPerPage = 10; // 每页显示的条数 (可调整)


// --- 计算属性 ---
// 根据筛选条件计算过滤后的日志列表
const filteredLogs = computed(() => {
  const typeFilter = filters.type;
  const codeFilter = filters.code.trim().toUpperCase();
  const dateFilter = filters.date;

  return allAlarmLogData.filter(log => {
    const typeMatch = !typeFilter || log.type === typeFilter;
    const codeMatch = !codeFilter || (log.code && log.code.toUpperCase().includes(codeFilter));
    // 日期筛选需要处理日期格式 'YYYY-MM-DD' 转换为 'YYYY/MM/DD'
    const dateMatch = !dateFilter || log.timestamp.startsWith(dateFilter.replace(/-/g, '/'));
    return typeMatch && codeMatch && dateMatch;
  });
});

// 根据过滤后的日志和分页状态计算当前页显示的日志
const paginatedLogs = computed(() => {
  const startIndex = (currentPage.value - 1) * itemsPerPage;
  const endIndex = startIndex + itemsPerPage;
  return filteredLogs.value.slice(startIndex, endIndex);
});

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(filteredLogs.value.length / itemsPerPage);
});

// --- 方法 ---

// 获取日志类型对应的 CSS class
const getLogTypeClass = (type) => {
  switch (type) {
    case 'Alarm':
      return 'type-alarm'; // 需要在全局定义这些 class 和颜色变量
    case 'Event':
      return 'type-event';
    case 'Info':
      return 'type-info';
    default:
      return '';
  }
};

// 应用筛选 (触发计算属性重新计算)
const applyFilters = () => {
  console.log('Applying filters:', {...filters});
  currentPage.value = 1; // 应用新筛选时重置到第一页
  // filteredLogs 和 paginatedLogs 计算属性会自动更新
};

// 刷新日志数据
const refreshLogs = async () => {
  await loadAlarmLogs();
};

// 加载报警日志数据
const loadAlarmLogs = async () => {
  try {
    // 设置加载状态
    isLoading.value = true;
    
    // 从主进程获取报警日志数据
    const alarmLogsData = await window.electronAPI.alarmLogs.getAll();
    
    // 清空现有数据
    allAlarmLogData.length = 0;
    
    if (Array.isArray(alarmLogsData) && alarmLogsData.length > 0) {
      // 转换数据格式并添加到数组
      alarmLogsData.forEach(log => {
        allAlarmLogData.push({
          timestamp: new Date(log.timestamp).toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
          }).replace(/\//g, '/'),
          type: log.level === 'error' ? 'Alarm' : (log.level === 'warn' ? 'Event' : 'Info'),
          code: log.code || '',
          description: log.message
        });
      });
      
      // 按时间戳倒序排列（最新的在前面）
      allAlarmLogData.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
    } else {
      console.log('没有找到报警日志数据或数据为空');
    }
  } catch (error) {
    console.error('加载报警日志失败:', error);
    alert(`加载报警日志失败: ${error.message || '未知错误'}`);
  } finally {
    // 结束加载状态
    isLoading.value = false;
  }
};

// 切换分页
const changePage = (direction) => {
  const newPage = currentPage.value + direction;
  if (newPage >= 1 && newPage <= totalPages.value) {
    currentPage.value = newPage;
    // paginatedLogs 计算属性会自动更新
  }
};

// 导出日志
const exportLogs = async () => {
  try {
    // 显示保存对话框，让用户选择保存位置和文件名
    const saveResult = await window.electronAPI.showSaveDialog({
      title: '导出报警日志',
      defaultPath: `报警日志_${new Date().toISOString().split('T')[0].replace(/-/g, '')}.csv`,
      filters: [
        { name: 'CSV文件', extensions: ['csv'] },
        { name: '所有文件', extensions: ['*'] }
      ]
    });
    
    if (saveResult.canceled) return;
    
    // 准备导出数据（使用筛选后的数据）
    const exportData = filteredLogs.value.map(log => {
      return {
        时间戳: log.timestamp,
        类型: log.type,
        代码: log.code || '-',
        描述: log.description
      };
    });
    
    // 发送到主进程进行保存
    const result = await window.electronAPI.exportToCSV({
      filePath: saveResult.filePath,
      data: exportData
    });
    
    if (result.success) {
      alert(`日志导出成功: ${saveResult.filePath}`);
    } else {
      throw new Error(result.error || '导出失败');
    }
  } catch (error) {
    console.error('导出日志失败:', error);
    alert(`导出日志失败: ${error.message || '未知错误'}`);
  }
};

// --- 生命周期钩子 ---
onMounted(async () => {
  console.log('报警日志页面已挂载');
  await loadAlarmLogs();
});
</script>

<style scoped>
/* 报警 / 事件日志页面组件特有的样式 */
/* 颜色变量、body 样式、Header 样式已移至 Header 组件或全局 */

/* --- Main Content Area Layout --- */
main {
  /* Tailwind classes handle most layout */
}

/* --- Page Title --- */
.page-title {
  /* styles defined with Tailwind */
}

/* --- Filter Area --- */
.filter-area {
  /* styles defined with Tailwind and custom classes */
}

.filter-group {
  /* styles defined with Tailwind */
}

.filter-label {
  /* styles defined with Tailwind */
}

.filter-input, .filter-select {
  /* styles defined with Tailwind and custom classes */
  /* Custom select arrow */
  appearance: none;
  background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%236b7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M6 8l4 4 4-4'/%3e%3c/svg%3e");
  background-position: right 0.3rem center;
  background-repeat: no-repeat;
  background-size: 1.2em 1.2em;
  padding-right: 2rem;
}

.hmi-button {
  /* styles defined with Tailwind and custom classes */
  transition: background-color 0.2s ease, border-color 0.2s ease, color 0.2s ease, box-shadow 0.2s ease;
}

.hmi-button-primary { /* background and color defined by variables */
}

.hmi-button-secondary { /* background and color defined by variables */
}


/* --- Log Table Area --- */
.log-table-container {
  /* flex-grow and overflow-y handled by Tailwind */
  /* background, border, shadow handled by Tailwind */
}

.log-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 0.75rem;
}

.log-table th, .log-table td {
  padding: 0.5rem 0.75rem;
  text-align: left;
  border-bottom: 1px solid var(--border-color); /* 需要在全局定义 --border-color */
  /* white-space handled by specific column classes */
}

.log-table th {
  background-color: #f9fafb;
  font-weight: 600;
  color: var(--text-secondary); /* 需要在全局定义 --text-secondary */
  position: sticky;
  top: 0;
  z-index: 10;
}

.log-table tbody tr:hover {
  background-color: #f0f4f8;
}

/* Specific column styles */
.col-timestamp {
  width: 130px;
  white-space: nowrap;
}

.col-type {
  width: 70px;
  text-align: center;
  font-weight: 600;
}

.col-code {
  width: 100px;
  white-space: nowrap;
}

.col-desc { /* Takes remaining space */
}


/* Log type colors -需要在全局定义这些变量 */
.type-alarm {
  color: var(--alarm-color);
}

.type-event {
  color: var(--event-color);
}

.type-info {
  color: var(--info-color);
}


/* --- Pagination Area --- */
.pagination-area {
  background-color: var(--bg-secondary); /* 需要在全局定义 --bg-secondary */
  padding: 0.5rem 1rem;
  border-top: 1px solid var(--border-color); /* 需要在全局定义 --border-color */
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-shrink: 0;
  font-size: 0.8rem;
  color: var(--text-secondary); /* 需要在全局定义 --text-secondary */
}

.pagination-controls {
  display: flex;
}

.pagination-controls button {
  /* Button styles defined with hmi-button hmi-button-secondary */
  margin-left: 0.5rem;
}

.pagination-info {
  font-weight: 500;
}

/* Body styles from original inline style */
/* max-width: 800px; max-height: 600px; margin: auto; */
/* In a Vue app, manage layout and centering within App.vue or specific layout components */

</style>